package cn.wit.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;

public class DemoFileOutPutStream {

	@Test
	public void testStream() {
		
		File file = new File("D://");//目录必须手动创建，如果没有得话
		
		File file1 = new File(file,"file.text");
		
//		FileOutputStream fo = null;
		
		try(FileOutputStream fo = new FileOutputStream(file1,true)) {
			//true就不会产生覆盖
//			fo = new FileOutputStream(file1,true);
			
			fo.write('A');//中文会乱码,字节流
			fo.write("ABC".getBytes());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void testFileInputStream() {
		
		File file = new File("D://");//目录必须手动创建，如果没有得话
		
		File file1 = new File(file,"file.text");
		
		try(FileInputStream fi = new FileInputStream(file1)) {
			
//			int c = fi.read();
//			
//			System.out.println((char)c);
			
			byte[] bytes = new byte[100];
			
			//可能数组没有装满
			int count = fi.read(bytes);
			
			//把有效得数组打印出来
			System.out.println(new String(bytes,0,count));
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
	}
	
	@Test
	public void testFileCopy() {
		
		//获取系统当前时间
		long start = System.currentTimeMillis();
		
		File source = new File("D://file.text");
		File target = new File("D://test.text");
		
		try (
				//读文件
				FileInputStream fi = new FileInputStream(source);
				//写文件
				FileOutputStream fo = new FileOutputStream(target);
		){

			byte[] contents = new byte[1024];
			
			while(true) {
				
				int count = fi.read(contents);
				if(count == -1) {
					break;
				}
				
				//读到多少位，就写多少位
				fo.write(contents, 0, count);
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		long end = System.currentTimeMillis();
		
		System.out.println((end-start));
		
	}
	
}
